package com.gitee.cashzhang27.test.boot.crypt.mapper.util;

import cn.hutool.core.util.ReflectUtil;
import com.gitee.cashzhang27.test.boot.crypt.mapper.entity.enums.DesensitizeType;
import com.google.common.base.Strings;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/07/11 16:56
 */
public class DesensitizeUtils {


  private static final String SETTER_PREFIX = "set";

  private static final String GETTER_PREFIX = "get";

  public static List<Object> desensitizeList(List<Object> paramList,
      Map<String, String> fieldNames) {
    paramList.forEach(param -> desensitizeObject(param, fieldNames));
    return paramList;
  }

  public static <T> T desensitizeObject(T param,
      Map<String, String> fieldNames) {
//    fieldNames.forEach((k, v) ->
//        ReflectionUtils
//            .invokeSetter(param, k,
//                desensitize(String.valueOf(ReflectionUtils.invokeGetter(param, k)), v))
//    );

    fieldNames.forEach((k, v) ->
        ReflectUtil.invoke(param, SETTER_PREFIX + StringUtils.capitalize(k), desensitize(
            ReflectUtil.invoke(param, GETTER_PREFIX + StringUtils.capitalize(k)), v))
    );
    return param;
  }

  private static String desensitize(String value, String type) {
    if (StringUtils.isBlank(value)) {
      return value;
    }
    int lastIndex = value.length() - 1;
    if (DesensitizeType.FULL_NAME.name().equals(type)) {
      return Strings.repeat("*", lastIndex) + value.charAt(lastIndex);
    } else if (DesensitizeType.ID_CARD.name().equals(type) || DesensitizeType.BANK_CARD.name()
        .equals(type)) {
      return value.substring(0, 4)
          + Strings.repeat("*", lastIndex - 7)
          + value.substring(lastIndex - 4, lastIndex);
    } else if (DesensitizeType.MOBILE_PHONE.name().equals(type)) {
      return value.substring(0, 3)
          + Strings.repeat("*", lastIndex - 6)
          + value.substring(lastIndex - 4, lastIndex);
    }
    return "******";
  }

  public static void main(String[] args) {
    //只保留最后一位
    String fullName = "宋鑫鹏";
    //中间十位脱敏
    String idCard = "420104199408267172";
    //保留前后四位
    String bankCard = "6222010100000000000";
    //保留前3位后4位
    String mobilePhone = "15314536754";
    System.out.println(desensitize(fullName, DesensitizeType.FULL_NAME.name()));
    System.out.println(desensitize(idCard, DesensitizeType.ID_CARD.name()));
    System.out.println(desensitize(bankCard, DesensitizeType.BANK_CARD.name()));
    System.out.println(desensitize(mobilePhone, DesensitizeType.MOBILE_PHONE.name()));
  }

}
